const numberUtil = require('./numberUtil')

function getIndex (target, filterModel) {
  for (let i = 0; i < target.length; i++) {
    const item = target[i]
    let same = true
    for (let key in filterModel) {
      if (filterModel[key] !== item[key]) {
        same = false
        break
      }
    }
    if (same) {
      return i
    }
  }
}

exports.findIndex = function (target, filterModel) {
  return getIndex(target, filterModel)
}

exports.findOne = function (target, filterModel) {
  return target[getIndex(target, filterModel)]
}

function getAverage (netValue, day, index) {
  let start = index - day + 1
  start = start < 0 ? 0 : start
  let count = 0
  for (let i = index; i >= start; i--) {
    count += netValue[i]['close']
  }
  return numberUtil.keepBtbDecimals(count / (index + 1 - start))
}

exports.getAverageList = function (netValue, day) {
  const list = []
  const newList = []
  netValue.forEach((item) => {
    newList.unshift(item)
  })
  newList.forEach((item, index) => {
    const average = getAverage(newList, day, index)
    list.push(average)
  })
  return list
}

exports.getAverageItem = function (netValue, day) {
  let count = 0
  for (let i = 0; i < day; i++) {
    count += netValue[i]['close']
  }
  return numberUtil.keepBtbDecimals(count / day)
}
